-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Add Middleware composition functions #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Hi, thanks for the contribution! I'm in favor of adding a helper type to chain middlewares, to avoid having to do it the manual way. But I'm not immediately convinced by your API, and I definitely wouldn't bake in an abbreviation like "MW" :) Have you seen https://github.com/justinas/alice? What do you think of that model? Is there something missing from an API like e.g. // Current
var e endpoint.Endpoint
e = myEndpoint
e = inner(param)(e)
e = outer(key, val)(e)
// Proposed e.g.
e := endpoint.Chain(outer(key, val), inner(param), myEndpoint) |
|
+1 I like it like |
|
I'm not particularly attached to function names or recursion vs. iteration. I do think that Chain should not be passed an endpoint, rather it should simply return a Middleware (chain) that can subsequently be applied to multiple endpoints (as in @anarcher's sample function) -- there's no point in rebuilding the same chain for multiple endpoints. Also, I think Chain is better written to require at least one Middlware. There's no reason to call Chain() if no Middleware is being passed, and if none are passed, there's no good return value without also returning an error (as the wrapper around the endpoint does nothing useful in that case). How about this: func Chain(outer Middleware, others ...Middleware) Middleware {
return func(e Endpoint) Endpoint {
for i := len(others) - 1; i >= 0; i-- { // reverse
e = others[i](e)
}
return outer(e)
}
} |
|
@shore It's better than my simple func. 👍 :-) |
|
Closed via #96! Thanks for the suggestion! |
Hi,
We like to reuse our middleware functions for various endpoints and like to put them in named functions. We have some composition functions that make this easy. In particular, we can compose individual middleware functions into chains, or we can compose more middleware functions onto the end of a chain. This also creates fewer anonymous functions than rewrapping all middleware for each endpoint.
http://play.golang.org/p/MQ5iTyr789
ReduceMW is analogous to the reduce / foldl functions. The composer is written such that the first MW function in the composition is the first one called, but it can trivially be replaced / altered to reverse the order if someone prefered the first function in the composition to instead be closest to the endpoint in the recursion.